﻿using Autofac;
using Autofac.Integration.WebApi;
using AutoMapper;
using Owin;
using System.Linq;
using System.Reflection;
using System.Web.Compilation;
using System.Web.Http;
using Yz.Cache;
using Yz.Core.Base;
using Yz.DataAccess.ModelMapper;

namespace Yz.ApiService
{
    public static class StartupExtension
    {  /// <summary>
       /// autofac的注入
       /// </summary>
       /// <param name="app"></param>
        public static void RegisterAutofac(this IAppBuilder app)
        {
            //创建autofac管理注册类的容器实例
            var builder = RegisterService();
            var config = GlobalConfiguration.Configuration;
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired();
            builder.RegisterWebApiFilterProvider(config);
            builder.RegisterWebApiModelBinderProvider();
            var container = builder.Build();
            app.UseAutofacMiddleware(container);
            app.UseWebApi(config);
            // Set the WebApi dependency resolver.
            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
        }

        /// <summary>
        /// autofac的注入
        /// </summary>
        /// <param name="app"></param>
        public static ContainerBuilder RegisterService()
        {
            //创建autofac管理注册类的容器实例
            var builder = new ContainerBuilder();

            #region 缓存注入 (手动注入) 
            builder.RegisterType<CacheManagerUitility>()
          .PropertiesAutowired(PropertyWiringOptions.AllowCircularDependencies).As<ICacheUitility>()
          .InstancePerLifetimeScope();
            #endregion

            #region autoMapper注入 
            builder.Register<IConfigurationProvider>(ctx => new MapperConfiguration(x =>
            {
                x.AddProfile<SourceProfileApi>();
                x.AddProfile<SourceProfileVm>();
            })).PropertiesAutowired(PropertyWiringOptions.AllowCircularDependencies).InstancePerLifetimeScope();
            //builder.Register<IMapper>(ctx => new Mapper(ctx.Resolve<IConfigurationProvider>(), ctx.Resolve)).InstancePerDependency();
            builder.RegisterType<Mapper>()
            .PropertiesAutowired(PropertyWiringOptions.AllowCircularDependencies).As<IMapper>()
            .InstancePerLifetimeScope();
            #endregion

            #region 实现接口IDependency 的自动注入
            var baseType = typeof(IDependency);
            var assemblys = BuildManager.GetReferencedAssemblies().Cast<Assembly>();
            builder.RegisterAssemblyTypes(assemblys.ToArray())
                  .Where(t => baseType.IsAssignableFrom(t) && t != baseType)
                  .PropertiesAutowired(PropertyWiringOptions.AllowCircularDependencies).AsImplementedInterfaces().InstancePerLifetimeScope();
            #endregion
            return builder;
        }
    }
}